﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
using EHTWebsiteProject.Code.BLL;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Text;
using EHTWebsiteProject.Code.Entity;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTCreateMenuIndex : System.Web.UI.Page
    {
        public Boolean IsVN = true;
        private String message = "";
        private Int32 MenuID = 0;
        private Int32 DM;
        
        private String languageCode = "vi-VN";
        private Int32 TypeDM = HangSo.DEFAULT_ID;
        private DataTable dtProductCategorys;
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources")); 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(EHTWebsiteProject.Administrator.EHTCreateMenuIndex));
                Session["value"] = null;

                dtProductCategorys = MenusProvider.GetMenusByLevel(6).Tables[0];
                try
                {
                    languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                    if (languageCode == "en-us")
                    {
                        IsVN = false;
                    }
                }
                catch (Exception ex) { }

                try
                {
                    MenuID = Int32.Parse(Request.QueryString["MenuID"]);
                }
                catch { }

                try
                {
                    TypeDM = Int32.Parse(Request.QueryString["ID"]);
                }
                catch { }
                Session["TypeDM"] = TypeDM.ToString();

                try
                {
                    DM = Int32.Parse(Request.QueryString["DM"]);
                }
                catch {
                    DM = TypeDM;
                }
                Session["DM"] = DM.ToString();


                try
                {
                    if (Request.QueryString["Message"]!= null)
                    {
                        message = Request.QueryString["Message"].ToString();                        
                        ltrErorr.Text = HelpMethod.ApplySuccess(message);
                    }
                    if (Request.QueryString["MessageErorr"] != null)
                    {
                        message = Request.QueryString["MessageErorr"].ToString();
                        ltrErorr.Text = HelpMethod.ErorrLogin(message);
                    }
                }
                catch { }

            
               
                if (MenuID != 0)
                {
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Edit_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Edit_Other;
                    GetDanhMucMenu(MenuID);               

                }
                else
                {
                    ViewState["action"] = HangSo.ACTION_ADD;
                    if (IsVN == true)
                        lbAdd_Edit.Text = HangSo.Add_VN;
                    else
                        lbAdd_Edit.Text = HangSo.Add_Other;
                }

                

                Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                LoadLanguage(Thread.CurrentThread.CurrentCulture);


                CreateDDLCategory(0, 0);

                if (IsVN == true)
                    this.ddlMenuCha.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
                else
                    this.ddlMenuCha.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));
                
                LoadUrl(Int32.Parse(Session["TypeDM"].ToString()));
                GetUrl();
                LoadDanhMucMenu();
                fixPathFileUpload();
                ddlDanhMucMenu.Enabled = false;

                String str = Session["ID"].ToString();
                ddlDanhMucMenu.SelectedValue = str;                
            }
        }

        /// <summary>
        /// Ham lay danh muc menu theo MenuID cha
        /// </summary>
        /// <param name="MenuID"></param>
        
        public void GetDanhMucMenu(Int32 MenuID)
        {
            Menus theMenus = MenusProvider.GetMenusByID(MenuID);
            txtMenuNameOther.Text = theMenus.MenuNameOther;
            txtMenuNameVN.Text = theMenus.MenuNameVN;
            txtThuTu.Text = theMenus.MenuOrder.ToString();
            ddlDanhMucMenu.SelectedValue = theMenus.ID.ToString();

            String str = theMenus.ControlUrl.ToString();

            if (Int32.Parse(Session["TypeDM"].ToString()) != 5)
            {
                //Ham cat chuoi lay List hoac ID                  
                Session["value"] = Int32.Parse(str.Split('=')[2]);

                //kiem tra chuoi url

                Boolean pagePro = str.Contains("Page=1");
                Boolean pageNews = str.Contains("Page=2");
                Boolean listPro = str.Contains("list");
                Boolean ID = str.Contains("ID");

                if (pagePro == true)
                {
                    if (listPro == true)
                        Session["TypeDM"] = 1;
                    if (ID == true)
                        Session["TypeDM"] = 2;
                }
                if (pageNews == true)
                {
                    if (listPro == true)
                        Session["TypeDM"] = 3;
                    if (ID == true)
                        Session["TypeDM"] = 4;
                }

            }
            else
            {               
                if(theMenus.ControlUrl.Trim() == "#")
                    ddlListPage.SelectedValue = "0";
                else
                    ddlListPage.SelectedValue = theMenus.ControlUrl.ToString();
            }
           
            if (theMenus.ParentID != 0)
                ddlMenuCha.SelectedValue = theMenus.ParentID.ToString();
            ViewState["action"] = HangSo.ACTION_UPDATE;
            ViewState["ID"] = MenuID;
            ViewState["Url"] = theMenus.ControlUrl;
            ViewState["IconTrangThai"] = theMenus.IconTrangThai;
            ViewState["MenuLevel"] = theMenus.MenuLevel;
            ViewState["Icon"] = theMenus.Icon;            
        }

        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbSave.Text = rm.GetString("lbSave", ci);            
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbMenuSub.Text = rm.GetString("lbMenuSub", ci);
            lbMenuNameVN.Text = rm.GetString("lbMenuNameVN", ci);
            lbMenuNameOther.Text = rm.GetString("lbMenuNameOther", ci);
            lbDanhMucMenu.Text = rm.GetString("lbDanhMucMenu", ci);
            lbParent.Text = rm.GetString("lbParent", ci);
            lbThuTu.Text = rm.GetString("lbThuTu", ci);
            btnOpen.Text = rm.GetString("btnOpen", ci);
            lbErorrChoisce.Text = rm.GetString("lbErorrChoisce",ci);
        }

        /// <summary>
        /// Ham load danh muc menu theo role
        /// </summary>

        [AjaxPro.AjaxMethod]
        public void LoadDanhMucMenu()
        {                                       
            if(DM == HangSo.MenuOther)
                ddlDanhMucMenu.DataSource = DanhMucMenusProvider.GetDanhMucMenus(HangSo.MenuOther);
            else
                ddlDanhMucMenu.DataSource = DanhMucMenusProvider.GetDanhMucMenus(HangSo.Index);

            ddlDanhMucMenu.DataTextField = "TitleOrder";
            ddlDanhMucMenu.DataValueField = "ID";
            ddlDanhMucMenu.DataBind();
            if (IsVN == true)
            {
                ddlDanhMucMenu.Items.Insert(0, new ListItem(HangSo.DanhMuc, "-1"));
            }
            else
            {
                ddlDanhMucMenu.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "-1"));
            }
        }
     
        /// <summary>
        /// Ham load menu cha
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [AjaxPro.AjaxMethod]
        private void CreateDDLCategory(Int32 ParentID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtProductCategorys.Select("ParentID = " + ParentID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["MenuID"].ToString());
                ListItem li;
                if (IsVN == true)
                    li = new ListItem(preString + drCategorysSub[i]["MenuNameVN"].ToString(), drCategorysSub[i]["MenuID"].ToString());
                else
                    li = new ListItem(preString + drCategorysSub[i]["MenuNameOther"].ToString(), drCategorysSub[i]["MenuID"].ToString());
                this.ddlMenuCha.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        /// <summary>
        /// Lay lien ket toi trang theo danh muc ID truyen vaof
        /// ID = 1: danh muc san pham
        /// 2: san pham;
        /// 3: danh muc tin tuc
        /// 4: Tin tuc:       
        /// </summary>
        /// <param name="ID"></param>

        public void LoadUrl(Int32 ID)
        {
            if (ID == 5)
            {
                txtUrl.Visible = false; ;
                btnOpen.Visible = false;
            }
            else
            {
                ddlListPage.Visible = false;
                txtUrl.Enabled = false;
                if (ID == 1)
                    txtUrl.Text = "default.aspx?Page=1&&list="; 
                if(ID == 2)
                    txtUrl.Text = "default.aspx?Page=1&&ID=";
                if (ID == 3)
                    txtUrl.Text = "default.aspx?Page=2&&list=";      
                if(ID == 4)
                    txtUrl.Text = "default.aspx?Page=2&&ID=";      
            }
            
        }


        /// <summary>
        /// Hàm lay danh sach cac trang cua index 
        /// </summary>
       
        public void fixPathFileUpload()
        {            
                ArrayList arrIndex = new ArrayList();
                DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/"));
                if (IsVN == true)
                    arrIndex.Add(new Item("0",HangSo.DanhMuc));
                else
                    arrIndex.Add(new Item("0", HangSo.DanhMucOther));  
                foreach (FileInfo file in dirInfo.GetFiles("*.aspx"))
                {
                    arrIndex.Add(new Item(file.Name.ToString(), file.Name.ToString()));
                }
                ddlListPage.DataSource = arrIndex;
                ddlListPage.DataTextField = "Ten1";
                ddlListPage.DataValueField = "Code1";
                ddlListPage.DataBind();          

        }

        /// <summary>
        /// Ham lay trang load vao cua so windown theo danh muc chon
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [AjaxPro.AjaxMethod]
        public String GetUrl()
        {
            String Url = "";
            Int32 ID = Int32.Parse(Session["TypeDM"].ToString());
            if (ID == 1)
                Url = "Chosice/ListProduct.aspx";
            if (ID == 2)
                Url = "Chosice/Sanpham.aspx";
            if (ID == 3)
                Url = "Chosice/ListNews.aspx";
            if (ID == 4)
                Url = "Chosice/News.aspx";
            return Url;
        }
        

        /// <summary>
        /// Ham kiem tra du lieu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public Boolean ValidateData()
        {
            Boolean flag = true;

            if (txtMenuNameOther.Text == "")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                flag = false;
            }

            if (txtMenuNameVN.Text == "")
            {
                if (IsVN == true)
                    message = HangSo.check_VN;
                else
                    message = HangSo.check_Other;
                flag = false;
            }

            if (ddlDanhMucMenu.SelectedValue == "-1")
            {
                if (IsVN == true)
                    message = HangSo.meagessddl;
                else
                    message = HangSo.meagessddlOther;
                flag = false;
            }

            if (TypeDM != 5)
            {
                if (Session["value"] == null)
                {
                    if (IsVN == true)
                        message = HangSo.LienKet;
                    else
                        message = HangSo.LienKetOther;
                    flag = false;

                }         
            }


            return flag;
        }

        /// <summary>
        /// Ham up load file len server
        /// </summary>
        /// <returns></returns>
        public String UpLoadFile()
        {
            String UploadFile = "";

            String action = ViewState["action"].ToString();
            if (this.fulIcon.HasFile)
            {
                String fileName = fulIcon.PostedFile.FileName;
                String pathAvatars = Server.MapPath("~/");
                String fileType = Path.GetExtension(fileName);
                String FileNewName = DateTime.Now.Ticks.ToString() + fileType;
                try
                {
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulIcon.PostedFile.InputStream);
                    if (Int32.Parse(oImg.Width.ToString()) > 50)
                    {


                        int thumbWidth = 50;
                        int thumbHeight = (Int32.Parse(oImg.Height.ToString()) * thumbWidth) / (Int32.Parse(oImg.Width.ToString()));
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oThumbNail.Save(pathAvatars + "\\ImageDatas\\Icons\\" + FileNewName);
                        oImg.Dispose();
                    }

                    else
                    {

                        this.fulIcon.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Icons//" + FileNewName);
                    }
                    ImgIcon.ImageUrl = "~\\ImageDatas\\Icons\\" + FileNewName;
                    UploadFile = FileNewName;
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                if (action != HangSo.ACTION_ADD)
                {
                    UploadFile = ViewState["Icon"].ToString();
                }
                else
                {                    
                        UploadFile = "icon-16-category.png";
                }
            }

            return UploadFile;
        }

        protected void ImgSave_Click(object sender, ImageClickEventArgs e)
        {
            TypeDM = Int32.Parse(Session["TypeDM"].ToString());
            String action = ViewState["action"].ToString();
            Int32 MenuIDOut = -1;
            if (ValidateData() == false)
            {
                Response.Redirect("EHTCreateMenuIndex.aspx?MenuID=" + MenuID + "&&ID="+Session["TypeDM"].ToString()+"&&MessageErorr="+message);
            }
            else
            {
                Menus theMenus = new Menus();
                theMenus.MenuOrder = Int32.Parse(txtThuTu.Text);
                theMenus.MenuNameVN = txtMenuNameVN.Text;
                theMenus.MenuNameOther = txtMenuNameOther.Text;
                theMenus.ID = Int32.Parse(ddlDanhMucMenu.SelectedValue.ToString());
                theMenus.Icon = UpLoadFile();
                if (ddlMenuCha.SelectedValue == "0")
                {
                    theMenus.MenuLevel = 1;
                    theMenus.ParentID = 0;
                }
                if (ddlMenuCha.SelectedValue != "0")
                {
                    theMenus.MenuLevel = 2;
                    theMenus.ParentID = Int32.Parse(ddlMenuCha.SelectedValue);
                }

                if (action == HangSo.ACTION_ADD)
                {
                    theMenus.MenuID = -1;
                    theMenus.IconTrangThai = "~//images//tick.png";

                    if (TypeDM == 5)
                    { 
                        if(ddlListPage.SelectedValue == "0")
                            theMenus.ControlUrl = "#";
                        else
                            theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();
                    }
                    else
                        theMenus.ControlUrl = txtUrl.Text + Session["value"].ToString();
                                                                 

                    MenuIDOut = MenusProvider.UIMenus(theMenus, true);
                }
                else
                {
                    theMenus.MenuID = Int32.Parse(ViewState["ID"].ToString());
                    theMenus.IconTrangThai = ViewState["IconTrangThai"].ToString();
                    theMenus.MenuLevel = Int32.Parse(ViewState["MenuLevel"].ToString());
                    if (TypeDM == 5)
                    {
                        if (ddlListPage.SelectedValue == "0")
                            theMenus.ControlUrl = "#";
                        else
                            theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();
                    }
                    else
                        theMenus.ControlUrl = txtUrl.Text + Session["value"].ToString();

                    MenuIDOut = MenusProvider.UIMenus(theMenus, false);
                }
                Response.Redirect("EHTMenusSub.aspx");
            }
        }

        protected void ImgApply_Click(object sender, ImageClickEventArgs e)
        {
            TypeDM = Int32.Parse(Session["TypeDM"].ToString());
            String action = ViewState["action"].ToString();
            Int32 MenuIDOut = -1;
            if (ValidateData() == false)
            {
                Response.Redirect("EHTCreateMenuIndex.aspx?MenuID=" + MenuID + "&&ID=" + Session["TypeDM"].ToString() + "&&MessageErorr=" + message);
            }
            else
            {
                Menus theMenus = new Menus();
                theMenus.MenuOrder = Int32.Parse(txtThuTu.Text);
                theMenus.MenuNameVN = txtMenuNameVN.Text;
                theMenus.MenuNameOther = txtMenuNameOther.Text;
                theMenus.ID = Int32.Parse(ddlDanhMucMenu.SelectedValue.ToString());
                theMenus.Icon = UpLoadFile();
                if (ddlMenuCha.SelectedValue == "0")
                {
                    theMenus.MenuLevel = 1;
                    theMenus.ParentID = 0;
                }
                if (ddlMenuCha.SelectedValue != "0")
                {
                    theMenus.MenuLevel = 2;
                    theMenus.ParentID = Int32.Parse(ddlMenuCha.SelectedValue);
                }

                if (action == HangSo.ACTION_ADD)
                {
                    theMenus.MenuID = -1;
                    theMenus.IconTrangThai = "~//images//tick.png";

                    if (TypeDM == 5)
                    {
                        if (ddlListPage.SelectedValue == "0")
                            theMenus.ControlUrl = "#";
                        else
                            theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();
                    }
                    else
                        theMenus.ControlUrl = txtUrl.Text + Session["value"].ToString();


                    MenuIDOut = MenusProvider.UIMenus(theMenus, true);
                }
                else
                {
                    theMenus.MenuID = Int32.Parse(ViewState["ID"].ToString());
                    theMenus.IconTrangThai = ViewState["IconTrangThai"].ToString();
                    theMenus.MenuLevel = Int32.Parse(ViewState["MenuLevel"].ToString());
                    if (TypeDM == 5)
                    {
                        if (ddlListPage.SelectedValue == "0")
                            theMenus.ControlUrl = "#";
                        else
                            theMenus.ControlUrl = ddlListPage.SelectedValue.ToString();
                    }
                    else
                        theMenus.ControlUrl = txtUrl.Text + Session["value"].ToString();

                    MenuIDOut = MenusProvider.UIMenus(theMenus, false);
                }

                String str = "";
                if (IsVN == true)
                    str = HangSo.App_VN;
                else
                    str = HangSo.App_Other;
                Response.Redirect("EHTCreateMenuIndex.aspx?MenuID=" + MenuIDOut +"&&Message="+str);
            }
        }
       
       
    }
}